package com.manage.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manage.dto.LocationDTO;
import com.manage.dto.add.LocationAddDTO;
import com.manage.dto.update.LocationUpdateDTO;
import com.manage.entity.Location;
import com.manage.result.PageResult;
import com.manage.server.mapper.LocationMapper;
import com.manage.server.service.LocationService;
import com.manage.vo.LocationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @description 针对表【location(地点表)】的数据库操作Service实现
 */
@Service
public class LocationServiceImpl extends ServiceImpl<LocationMapper, Location> implements LocationService {

    @Override
    public boolean save(LocationAddDTO locationAddDTO) {
        Location location = new Location();
        BeanUtils.copyProperties(locationAddDTO, location);
        return this.save(location);
    }

    @Override
    public boolean updateById(LocationUpdateDTO locationUpdateDTO) {
        Location location = new Location();
        BeanUtils.copyProperties(locationUpdateDTO, location);
        return super.updateById(location);
    }

    @Override
    public PageResult<LocationVO> findLocationByPage(LocationDTO dto) {
        // 1. 处理分页参数（修正参数顺序问题）
        int pageNum = dto.getPageNum() != null && dto.getPageNum() > 0 ? dto.getPageNum() : 1;
        int pageSize = dto.getPageSize() != null && dto.getPageSize() > 0 ? dto.getPageSize() : 10;

        // 2. 创建分页对象（注意参数顺序：current, size）
        Page<Location> page = new Page<>(pageNum, pageSize);

        // 3. 构建动态查询条件
        QueryWrapper<Location> queryWrapper = new QueryWrapper<>();

        // 地址模糊查询
        if (StringUtils.hasText(dto.getAddress())) {
            queryWrapper.like("address", dto.getAddress().trim());
        }

        // 精确匹配条件
        if (dto.getId() != null) {
            queryWrapper.eq("id", dto.getId());
        }
        if (dto.getIsActive() != null) {
            queryWrapper.eq("is_active", dto.getIsActive());
        }

        // 4. 执行分页查询
        Page<Location> resultPage = this.page(page, queryWrapper);

        // 5. 转换Entity到VO（处理特殊字段）
        Page<LocationVO> voPage = (Page<LocationVO>) resultPage.convert(entity -> {
            LocationVO vo = new LocationVO();
            BeanUtils.copyProperties(entity, vo);
            // 处理数据库字段和VO字段不一致的情况（如果有）
            // vo.setXXX(entity.getXXX());
            return vo;
        });

        // 6. 返回分页结果
        return PageResult.success(voPage);
    }
}